package com.smartsofa.main;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.smartsofa.R;
import com.smartsofa.util.AsyncImageLoader;
import com.smartsofa.util.ChangeInformation;
import com.smartsofa.util.MyUtils;
import com.smartsofa.util.Tools;
public class UserInfoActivity extends Activity implements OnClickListener {
	 
	RelativeLayout rl_image;
	RelativeLayout rl_name;
	RelativeLayout rl_tele;
	RelativeLayout rl_device;
	RelativeLayout rl_gender;
	RelativeLayout rl_weight;
	RelativeLayout rl_height;
	RelativeLayout rl_birth;
	
	private TextView user_name;
	private TextView telenumber;
	private TextView deviceid;
	private TextView gender;
	private TextView weight;
	private TextView height;
	private TextView birthday;
	private Button back;

	private ImageView user_image;
	private String[] items = new String[] { "选择本地图片", "拍照" };
	private String[] genderitems = new String[] { "男", "女" };
	/* 头像名称 */
	private static final String IMAGE_FILE_NAME = "user_img_"+MyUtils.getUSERID()+".png";
	private  String fileName;

	/* 请求码 */
	private static final int IMAGE_REQUEST_CODE = 0;
	private static final int CAMERA_REQUEST_CODE = 1;
	private static final int RESULT_REQUEST_CODE = 2;
	private static String path="/sdcard/myInformation/";
	
	private static final String TAG = "uploadFile";   
    private static final int TIME_OUT = 10*10000000; //超时时间   
    private static final String CHARSET = "utf-8"; //设置编码   
    public static final String SUCCESS="1"; 
    public static final String FAILURE="0";   
    
    private String photostr;
    private Thread thread;
	
@Override
protected void onCreate(Bundle savedInstanceState) {
	
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_userinfo);
	rl_image = (RelativeLayout) findViewById(R.id.userinfo_1);
	rl_name = (RelativeLayout) findViewById(R.id.userinfo_2);
	rl_tele = (RelativeLayout) findViewById(R.id.userinfo_3);
	rl_device = (RelativeLayout) findViewById(R.id.userinfo_4);
	rl_gender = (RelativeLayout) findViewById(R.id.userinfo_5);
	rl_weight = (RelativeLayout) findViewById(R.id.userinfo_6);
	rl_height=(RelativeLayout) findViewById(R.id.userinfo_7);
	rl_birth = (RelativeLayout) findViewById(R.id.userinfo_8);
	back=(Button)findViewById(R.id.bt_info_back);
	rl_image.setOnClickListener(this);
	rl_name.setOnClickListener(this);
	rl_tele.setOnClickListener(this);
	rl_device.setOnClickListener(this);
	rl_gender.setOnClickListener(this);
	rl_weight.setOnClickListener(this);
	rl_height.setOnClickListener(this);
	rl_birth.setOnClickListener(this);
	back.setOnClickListener(this);
	
	user_image = (ImageView) findViewById(R.id.info_user_image);
	String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
	String fileName = "/user_img_"+MyUtils.getUSERID()+".png";
	Bitmap bitmap = BitmapFactory.decodeFile(baseDir+fileName);
	if(bitmap != null){
		user_image.setImageBitmap(bitmap);
		photostr = convertIconToString(bitmap);
	}
	else{
		SharedPreferences userinfo = getSharedPreferences("userInformation", 0);
		String user_img_url= userinfo.getString("imageurl", "");
		if(!("").equals(user_img_url)){
			AsyncImageLoader imageLoader=new AsyncImageLoader(getApplicationContext());
			Bitmap bitmap2 = imageLoader.loadImage(user_image, user_img_url);
			if (bitmap2 != null) {
				user_image.setImageBitmap(bitmap2);
				MyUtils.setPicToStore(MyUtils.getUSERID(),bitmap2);
			}
		}
	}
	user_name = (TextView) findViewById(R.id.user_name);
	telenumber = (TextView) findViewById(R.id.user_telenumber);
	gender = (TextView) findViewById(R.id.user_gender);
	weight = (TextView) findViewById(R.id.user_weight);
	height= (TextView) findViewById(R.id.user_height);
	birthday = (TextView) findViewById(R.id.user_birthdate);
	deviceid =(TextView) findViewById(R.id.user_diviceid);
	
	SharedPreferences useinfo = getSharedPreferences("userInformation", 0);
	String username = useinfo.getString("username", "用户名");
	String telenumbers = useinfo.getString("telenumber", "00000000000");
	String deviceids = useinfo.getString("deviceid", "0000000");
	String weights = useinfo.getString("weight", "0");
	String heights = useinfo.getString("height", "0");
	String genders = useinfo.getString("gender", "1");
	String birthdays = useinfo.getString("birthday", "1990-01-01");
	String imageurl = useinfo.getString("imageurl", "null");
	Log.i("imageurl", imageurl);
	user_name.setText(username);
	telenumber.setText(telenumbers);
	deviceid.setText(deviceids);
	if(!weight.equals("")){
		weight.setText(weights+"Kg");
	}
	if(!height.equals("")){
		height.setText(heights+"cm");
	}
	if(genders.equals("1")){
		gender.setText("男");
	}
	else{
		gender.setText("女");
	}
	birthday.setText(birthdays);
			
}




@Override
public void onClick(View v) {
	Intent intent = new Intent(getApplicationContext(),ChangeInformation.class);
	switch(v.getId()){
	case R.id.userinfo_1:
		showDialog();
		break;
	case R.id.userinfo_2:
		startActivityForResult(intent, 3);	
		break;
	case R.id.userinfo_3:
		startActivityForResult(intent, 4);
	break;
	case R.id.userinfo_4:
		startActivityForResult(intent, 5);
	break;
	case R.id.userinfo_5:
		new AlertDialog.Builder(this).setTitle("设置性别").setItems(genderitems, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				SharedPreferences sharedPreferences = getSharedPreferences("userInformation",0);
				Editor editor;
				thread = new Thread(new sendInfoToServer());
				switch (which) {
				case 0:
					
					editor = sharedPreferences.edit();
					editor.putString("gender", "1");
				    editor.commit();
				    gender.setText("男");
				    
					thread.start();
					break;
					
				case 1:
					
					editor = sharedPreferences.edit();
					editor.putString("gender", "2");
				    editor.commit();
				    gender.setText("女");
				    
					thread.start();
					break;

				default:
					break;
				}
				
			}
		}).setNegativeButton("取消", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		}).show();
	break;
	case R.id.userinfo_6:
		startActivityForResult(intent, 6);
	break;
	case R.id.userinfo_7:
		startActivityForResult(intent, 6);
	break;
	case R.id.userinfo_8:
		
		DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
			
			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear,
					int dayOfMonth) {
			SharedPreferences sharedPreferences = getSharedPreferences("userInformation", 0);
			Editor editor = sharedPreferences.edit();
			editor.putString("birthday", year+"-"+(monthOfYear+1)+"-"+dayOfMonth);
			editor.commit();
			birthday.setText(year+"-"+(monthOfYear+1)+"-"+dayOfMonth);
			thread = new Thread(new sendInfoToServer());
			thread.start();
			
				
			}
		};
		DatePickerDialog  datePicker = new DatePickerDialog(UserInfoActivity.this, dateSetListener, 1990, 0, 1);

		datePicker.show();
		break;
	case R.id.bt_info_back:
		UserInfoActivity.this.finish();
		break;
	}
	
}
/**
 * 显示选择对话框
 */
private void showDialog() {

	new AlertDialog.Builder(this)
			.setTitle("设置头像")
			.setItems(items, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					switch (which) {
					case 0:
						Intent intentFromGallery = new Intent();
						intentFromGallery.setType("image/*"); // 设置文件类型
						intentFromGallery
								.setAction(Intent.ACTION_GET_CONTENT);
						startActivityForResult(intentFromGallery,
								IMAGE_REQUEST_CODE);
						
						break;
					case 1:

						Intent intentFromCapture = new Intent(
								MediaStore.ACTION_IMAGE_CAPTURE);
						// 判断存储卡是否可以用，可用进行存储
						if (Tools.hasSdcard()) {

							intentFromCapture.putExtra(
									MediaStore.EXTRA_OUTPUT,
									Uri.fromFile(new File(Environment
											.getExternalStorageDirectory(),
											IMAGE_FILE_NAME)));
						}

						startActivityForResult(intentFromCapture,
								CAMERA_REQUEST_CODE);
						break;
					}
				}
			})
			.setNegativeButton("取消", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			}).show();

}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	//结果码不等于取消时候
	if (resultCode != RESULT_CANCELED) {
		SharedPreferences userinfo = getSharedPreferences("userInformation", 0);
		Editor editor ;
		String string ;
		switch (requestCode) {
		case IMAGE_REQUEST_CODE:
			startPhotoZoom(data.getData());
			break;
		case CAMERA_REQUEST_CODE:
			if (Tools.hasSdcard()) {
				File tempFile = new File(
						Environment.getExternalStorageDirectory()
								,IMAGE_FILE_NAME);
				startPhotoZoom(Uri.fromFile(tempFile));
			} else {
				Toast.makeText(getApplicationContext(), "未找到存储卡，无法存储照片！",
						Toast.LENGTH_LONG).show();
			}
			break;
		case RESULT_REQUEST_CODE:
			if (data != null) {
				getImageToView(data);
			}
			break;
		case 3:
			string = data.getStringExtra("changeinfo");
			
			editor  = userinfo.edit();
		    editor.putString("username", string);
		    editor.commit();
			this.user_name.setText(string);
			break;
		case 4:
			string = data.getStringExtra("changeinfo");			
		    editor  = userinfo.edit();
		    editor.putString("telenumber", string);
		    editor.commit();
			this.telenumber.setText(string);
			break;
		case 5:
			string = data.getStringExtra("changeinfo");
			editor  = userinfo.edit();
		    editor.putString("deviceid", string);
		    editor.commit();
			this.deviceid.setText(string);
			break;
		case 6:
			string = data.getStringExtra("changeinfo");
			editor  = userinfo.edit();
		    editor.putString("weight", string);
		    editor.commit();
			this.weight.setText(string);
			break;
		case 7:
			string = data.getStringExtra("changeinfo");
			editor  = userinfo.edit();
		    editor.putString("height", string);
		    editor.commit();
			this.height.setText(string);
			break;
		}
	}
	Thread thread = new Thread(new sendInfoToServer());
	thread.start();
	super.onActivityResult(requestCode, resultCode, data);
}

/**
 * 裁剪图片方法实现
 * 
 * @param uri
 */
public void startPhotoZoom(Uri uri) {

	Intent intent = new Intent("com.android.camera.action.CROP");
	intent.setDataAndType(uri, "image/*");
	// 设置裁剪
	intent.putExtra("crop", "true");
	// aspectX aspectY 是宽高的比例
	intent.putExtra("aspectX", 1);
	intent.putExtra("aspectY", 1);
	// outputX outputY 是裁剪图片宽高
	intent.putExtra("outputX", 150);
	intent.putExtra("outputY", 150);
	intent.putExtra("return-data", true);
	startActivityForResult(intent, 2);
}

/**
 * 保存裁剪之后的图片数据
 * 
 * @param picdata
 */
private void getImageToView(Intent data) {
	Bundle extras = data.getExtras();
	if (extras != null) {
		Bitmap photo = extras.getParcelable("data");
		photostr=convertIconToString(photo);
		BitmapDrawable drawable = new BitmapDrawable(photo);
		user_image.setImageDrawable(drawable);
		MyUtils.setPicToStore(MyUtils.getUSERID(),photo);
		/**
		 * 将图片上传至服务器端
		 */
	    Thread thread = new Thread(new sendPicToServer());
	    thread.start();
	}
}

class sendInfoToServer implements Runnable{

	@Override
	public void run() {
		try {
			SharedPreferences useinfo = getSharedPreferences("userInformation", 0);
			String username = URLEncoder.encode(useinfo.getString("username", "username"));
			String telenumbers = URLEncoder.encode(useinfo.getString("telenumber", "password"));
			String deviceids = URLEncoder.encode(useinfo.getString("deviceid", "0000000"));
			String weights = URLEncoder.encode(useinfo.getString("weight", "0"));
			String heights = URLEncoder.encode(useinfo.getString("height", "0"));
			String genders = useinfo.getString("gender", "1");
			String birthdays = URLEncoder.encode(useinfo.getString("birthday", "1990-01-01"));
			//String imageurlString = URLEncoder.encode(useinfo.getString("imageurl", ""));
			String url =MyUtils.getUrl()+"user_updatePersonal?userid="+MyUtils.getUSERID() +
					"&username="+username+"&phonenum="+telenumbers+"&deviceid="+deviceids+
					"&gender="+genders+"&weight="+weights+"&height="+heights+"&birthday="+birthdays;
			Log.i("url",url);
			
				HttpGet request = new HttpGet(url);	
				// 发送请求
			   BasicHttpParams httpParams = new BasicHttpParams();
			   HttpConnectionParams.setConnectionTimeout(httpParams,MyUtils.REQUEST_TIMEOUT);
		       HttpClient httpClient = new DefaultHttpClient(httpParams);
		       HttpResponse httpResponse = httpClient.execute(request);					       
		       	
		      if (httpResponse.getStatusLine().getStatusCode() == 200) {
			        String jsonString = EntityUtils.toString(httpResponse.getEntity());
			        Log.i("jsonString", jsonString);
			        JSONObject json = new JSONObject(jsonString);
			        Boolean flag=(Boolean) json.get("success");	
			        String return_msg=json.getString("msg");
			        Log.i("flag", ""+flag);
			        Log.i("jasonmag",return_msg);
		      }
		      }catch (Exception e) {
		        	 e.printStackTrace();
		      }
		
	}
	
}
 class sendPicToServer implements Runnable{
	 
	 @Override
	 public void run() {	
		 String urlString = MyUtils.getUrl()+"img_uploadfile"; 
		 HttpPost post;
		try {
			post = new HttpPost(new URI(urlString));
			JSONObject json = new JSONObject();
		
			json.put("fileData",photostr);	
			json.put("userId", MyUtils.getUSERID());			
			post.setEntity(new StringEntity(json.toString(),"utf-8"));
			BasicHttpParams httpParams = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParams,3000);
			HttpClient httpClient = new DefaultHttpClient(httpParams);
			HttpResponse httpResponse = httpClient.execute(post);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = httpResponse.getEntity();
				Log.i("send png to server", "success!");
				if (entity != null) {
					// 获取服务器响应的json字符串
					String jsonobj = EntityUtils.toString(entity);
				    Log.i("jsonobj", jsonobj);	
					JSONObject jsonObject = new JSONObject(jsonobj);
				    int flag=jsonObject.getInt("flag");
					/*String imageurl = jsonObject.getString("imageurl");
					Log.i("imageurl", imageurl);
					SharedPreferences useinfo = getSharedPreferences("userInformation", 0);
					Editor editor  = useinfo.edit();
					editor.putString("imageurl", imageurl);
					editor.commit(); */
					
				}
			}		
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (URISyntaxException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
	
	 }
 }
 public static String convertIconToString(Bitmap bitmap)  
 {  
     ByteArrayOutputStream baos = new ByteArrayOutputStream();// outputstream  
     bitmap.compress(CompressFormat.PNG, 100, baos);  
     byte[] appicon = baos.toByteArray();// 转为byte数组  
     return Base64.encodeToString(appicon, Base64.DEFAULT);  
 }
 
}



